# -*- coding: utf-8 -*-
from scpy.logger import get_logger
import os
import sys
import json
from cassandra.cluster import Cluster
from cassandra.query import dict_factory
from cassandra.auth import PlainTextAuthProvider
from config import *
reload(sys)
sys.setdefaultencoding('utf-8')

logger = get_logger(__file__)

CURRENT_PATH = os.path.dirname(__file__)
if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"


class cassendra(object):
    def __init__(self, cassendraKeySpace, cassendraHost, auth_provider):
        self.cluster = Cluster(contact_points=cassendraHost, auth_provider=auth_provider)
        self.session = self.cluster.connect(cassendraKeySpace)

    def save_to_cassendra_resume(self,result):
        self.session.execute(
        """
        INSERT INTO resume_hqrm_by_company_name (companyName, period, createdAt, jsonData)
        VALUES (%s, %s, %s, %s)
        """,
        (result['companyName'], result['period'], result['createdAt'], json.dumps(result['resumeList']))
        )

    def save_to_cassendra_resume_source(self,result):
        self.session.execute(
        """
        INSERT INTO resume_src_by_url (url, createdAt,html)
        VALUES (%s, %s, %s)
        """,
        (result['url'], result['createdAt'], result['html'])
        )

    def save_to_cassandra_juxian_resume(self, result):
        self.session.execute(
            """
            INSERT INTO resume_juxian_by_company_name (companyName, period, createdAt, jsonData)
            VALUES (%s, %s, %s, %s)
            """,
            (result['companyName'], result['period'], result['createdAt'], json.dumps(result['jsonData']))
        )

    def save_to_cassandra_monitor_resume(self, result):
        self.session.execute(
            """
            INSERT INTO resume_monitor_by_company_name (companyName, period, createdAt, jsonData)
            VALUES (%s, %s, %s, %s)
            """,
            (result['companyName'], result['period'], result['createdAt'], json.dumps(result['jsonData']))
        )

    def find_companyName_list(self):
        self.session.row_factory = dict_factory
        query = "SELECT companyName FROM resume_hqrm_by_company_name"
        companyNameList = self.session.execute(query)
        return companyNameList

    def find_company_resume(self,companyName):
        self.session.row_factory = dict_factory
        query = "SELECT * FROM resume_hqrm_by_company_name WHERE companyName='%s' LIMIT 1"%companyName
        rows = self.session.execute(query)
        return rows

if __name__ == '__main__':
    pass